package util

import (
	"bgs/conf"
	"bgs/db"
	sqlc "bgs/db/sqlc"
	"context"
	"fmt"
	"go.uber.org/zap"
)

// NsqFailOver proxy wxpay nsq message
type NsqFailover struct {
	dao  *db.PgDao
	slog *zap.SugaredLogger
	vars *conf.VarsSection
}

// NewNsqFailOver initialization
func NewNsqFailover(
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
	vars *conf.VarsSection,
) *NsqFailover {
	return &NsqFailover{
		dao:  pgdao,
		slog: slog.With("module", "NsqFailover"),
		vars: vars,
	}
}

// BackupSubMsgParam
type BackupSubMsgParam struct {
	Ts    int64
	Topic string
	Mbody []byte
}

// BackupSubMsgWhenHandleFail go func 执行
func (s *NsqFailover) BackupSubMsgWhenHandleFail(ctx context.Context, err *error, p BackupSubMsgParam) {
	var errMsg string
	if r := recover(); r != nil {
		errMsg = fmt.Sprintf("nsq recover panic:%s", r)
	} else if err != nil && (*err) != nil {
		errMsg = fmt.Sprintf("nsq normal err:%s", (*err).Error())
	}
	if errMsg != "" {
		q := s.dao.Q
		sqlErr := q.UpsertNsqFail(ctx, sqlc.UpsertNsqFailParams{
			IsSub:   true,
			Ts:      p.Ts,
			Topic:   p.Topic,
			Message: p.Mbody,
			ErrMsg:  errMsg,
		})
		if sqlErr != nil {
			s.slog.Infof("BackupSubMsg err:%v", sqlErr)
		}
	}
}
